package com.coderli.onecoder.agent.common;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.coderli.onecoder.agent.task.CommandExecutorPool;
import com.coderli.onecoder.agent.task.SimpleCommandPool;
import com.coderli.onecoder.shared.model.CommandRequest;

/**
 * 用于处理来自服务端的命令
 * 
 * @author lihzh
 * @date 2012-6-29 下午5:05:26
 */
public class AgentCommandHandler extends SimpleChannelHandler {

	private static final Logger log = LoggerFactory.getLogger(AgentCommandHandler.class);
	private CommandExecutorPool commandExecutorPool;
	
	public AgentCommandHandler() {
		this.commandExecutorPool = new SimpleCommandPool();
	}

	/**
	 * 当Agent和Server连接绑定时，处理相关业务
	 * 
	 * @author lihzh
	 * @date 2012-7-3 上午10:36:06
	 */
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		log.info("Channel connected.");
		// 初始化Agent Task线程池,默认使用SimplePool 
		initAgentTaskPool();
		// 发送Agent信息
		sendAgentInfo(e.getChannel());
	}

	/**
	 * 初始化Agent任务线程池
	 * 
	 * @author lihzh
	 * @param commandPool
	 *            Agent命令线程池
	 * @date 2012-7-4 下午3:21:22
	 */
	private void initAgentTaskPool() {
		// 初始化池
		commandExecutorPool.init();
	}
	
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		CommandRequest request = (CommandRequest) e.getMessage();
		commandExecutorPool.runTask(request);
	}

	/**
	 * 仅在与Server绑定的时候，向Server端发送当前Agent信息，以便Server分析和持久化处理
	 * 
	 * @param channel
	 *            消息频道
	 * @author lihzh
	 * @date 2012-7-3 下午3:27:25
	 */
	private void sendAgentInfo(Channel channel) {
		// 从Config中获取AgentInfo信息
		channel.write(AgentConfig.getConfig().getAgentInfo());
	}

}
